<?php
/**
 * 배추통합검색  (UnitedSearch for Gnuboard4)
 *
 * Copyright (c) 2010 Choi Jae-Young <www.miwit.com>
 *
 * 저작권 안내
 * - 저작권자는 이 프로그램을 사용하므로서 발생하는 모든 문제에 대하여 책임을 지지 않습니다. 
 * - 이 프로그램을 어떠한 형태로든 재배포 및 공개하는 것을 허락하지 않습니다.
 * - 이 저작권 표시사항을 저작권자를 제외한 그 누구도 수정할 수 없습니다.
 */


if (!defined("_GNUBOARD_")) exit; // 개별 페이지 접근 불가 

// 동기화
function mw_sync_united_search()
{
    global $g4, $mwus;

    sql_query("delete from $mwus[search_table]");

    $qry = sql_query("select * from $g4[board_table]");
    while ($row = sql_fetch_array($qry)) {
	$write_table = $g4[write_prefix].$row[bo_table];
	sql_query("insert into $mwus[search_table] select '$row[gr_id]', '$row[bo_table]', wr_id, wr_parent, wr_is_comment, mb_id, wr_option, wr_subject, wr_content, wr_datetime from $write_table", false);
    }
}

// 검색
function mw_get_united_search($stx, $rows=10, $gr_id, $group)
{
    global $g4, $mwus, $page, $is_admin, $member;

    if (!is_numeric($page)) $page = 1;

    $board_info = array();
    $board_reject = array();
    $tmp = array();

    // 그룹 접근 권한
    if ($group[gr_use_access]) {
        $row = sql_fetch("select * from $g4[group_member_table] where gr_id = '{$us_group[$i]}' and mb_id = '$member[mb_id]'");
        if (!$row) return array();
    }

    // 인기검색어
    $sql = " insert into $g4[popular_table] set pp_word = '$stx', pp_date = '$g4[time_ymd]', pp_ip = '$_SERVER[REMOTE_ADDR]' ";
    sql_query($sql, FALSE);

    // 게시판 전체검색 사용, 목록보기 권한
    $sql = "select * from $g4[board_table] where gr_id = '$gr_id'";
    $qry = sql_query($sql);
    while ($row = sql_fetch_array($qry))
    {
	$board_info[$row[bo_table]] = $row;

	//if (!$row[bo_use_search]) $board_reject[] = $row[bo_table];

        if ($row[bo_list_level] > $member[mb_level] || !$row[bo_use_search])
            $board_reject[] = $row[bo_table];
    }

    $sql_common = " from $mwus[search_table] ";
    $sql_search = " where (";

    if (!$mwus[us_sop]) $mwus[us_sop] = "and";

    $tmp = explode(" ", $stx);
    $a = 0;
    for ($i=0; $i<count($tmp); $i++) {
        $tmp[$i] = trim($tmp[$i]);
        if (!strlen($tmp[$i])) continue;
        if ($a++) $sql_search .= " {$mwus[us_sop]} ";
        switch ($mwus[us_sfl]) {
            case "wr_subject": $sql_search .= " INSTR(replace(wr_subject, ' ', ''), '{$tmp[$i]}') "; break;
            case "wr_content": $sql_search .= " INSTR(replace(wr_content, ' ', ''), '{$tmp[$i]}') "; break;
            case "wr_subject,wr_content": $sql_search .= " (INSTR(replace(wr_subject, ' ', ''), '{$tmp[$i]}') or INSTR(replace(wr_content, ' ', ''), '{$tmp[$i]}')) "; break;
        }
    }

    $sql_search.= ") and gr_id = '$gr_id' ";
    $sql_order = " order by wr_datetime desc ";
    $sql_group = " group by wr_parent, bo_table ";

    //if (sizeof($board_reject) && $is_admin != "super")
	$sql_search .= " and bo_table not in ('". implode("','", $board_reject) ."') ";

    $sql = "select count(distinct wr_parent, bo_table) as cnt
	    $sql_common
	    $sql_search" ;
    $row = sql_fetch($sql);
    $total_count = $row[cnt];

    $total_page  = @ceil($total_count / $rows);  // 전체 페이지 계산
    if ($page == "") { $page = 1; } // 페이지가 없으면 첫 페이지 (1 페이지)
    $from_record = ($page - 1) * $rows; // 시작 열을 구함  */

    $sql = "select *
	    $sql_common
	    $sql_search
	    $sql_group
	    $sql_order
	    limit $from_record, $rows ";
    $qry = sql_query($sql);

    $list = array();
    $list[total_page] = $total_page;

    for ($i=0; $row=sql_fetch_array($qry); $i++) {
	$list[$i] = $row;
	$list[$i][num] = $total_count - ($page - 1) * $rows - $i;

	$list[$i][board] = $board_info[$row[bo_table]]; // 게시판 정보

	$list[$i][wr_date] = date("Y.m.d", strtotime($list[$i][wr_datetime]));
	$list[$i][board_href] = "$g4[bbs_path]/board.php?bo_table=$row[bo_table]";
	$list[$i][href] = $list[$i][board_href];
	$list[$i][subject] = get_text($row[wr_subject]);

	if ($row[wr_is_comment]) {
	    $row2 = sql_fetch("select * from $mwus[search_table] where bo_table = '$row[bo_table]' and wr_id = '$row[wr_parent]'");
	    $list[$i][subject] = get_text($row2[wr_subject]);
            if (strstr($row2[wr_option], 'secret'))
	        $list[$i][wr_option] = $row2[wr_option];
	    $list[$i][href].= "&wr_id=$row[wr_parent]#c$row[wr_id]";
	} else {
	    $list[$i][href].= "&wr_id=$row[wr_id]";
	}

        if ($member[mb_id]) {
            $list[$i][subject] = str_replace("{닉네임}", $member[mb_nick], $list[$i][subject]);
            $list[$i][subject] = str_replace("{별명}", $member[mb_nick], $list[$i][subject]);
        } else {
            $list[$i][subject] = str_replace("{닉네임}", "회원", $list[$i][subject]);
            $list[$i][subject] = str_replace("{별명}", "회원", $list[$i][subject]);
        }

	$list[$i][content] = cut_str(get_text(strip_tags($row[wr_content])), 200);
        $list[$i][content] = str_replace("&nbsp;", "", $list[$i][content]);
	$list[$i][subject] = str_replace($stx, "<span class='us_stress'>$stx</span>", $list[$i][subject]);
	$list[$i][content] = str_replace($stx, "<span class='us_stress'>$stx</span>", $list[$i][content]);

        if ($board_info[$row[bo_table]][bo_read_level] > $member[mb_level]) {
            //$list[$i][subject] = "글 읽기 권한이 없습니다.";
            $list[$i][wr_content] = "글 읽기 권한이 없습니다.";
            $list[$i][content] = $list[$i][wr_content];
        }

        if (strstr($list[$i][wr_option], "secret") && $list[$i][mb_id] != $member[mb_id] && $is_admin != "super") {
            $list[$i][wr_content] = "비밀 글 입니다.";
            $list[$i][content] = $list[$i][wr_content];
        }

        $thumb1 = "$g4[path]/data/file/{$row[bo_table]}/thumbnail/{$row[wr_parent]}";
        $thumb2 = "$g4[path]/data/file/{$row[bo_table]}/thumbnail2/{$row[wr_parent]}";
        $thumb3 = "$g4[path]/data/file/{$row[bo_table]}/thumbnail3/{$row[wr_parent]}";
        $thumb4 = "$g4[path]/data/file/{$row[bo_table]}/thumb/{$row[wr_parent]}";

        $list[$i][thumb] = "";
        if (file_exists("$thumb1.jpg")) $list[$i][thumbnail] = "$thumb1.jpg";
        elseif (file_exists("$thumb2.jpg")) $list[$i][thumbnail] = "$thumb2.jpg";
        elseif (file_exists("$thumb3.jpg")) $list[$i][thumbnail] = "$thumb3.jpg";
        elseif (file_exists("$thumb4.jpg")) $list[$i][thumbnail] = "$thumb4.jpg";
        elseif (file_exists($thumb1)) $list[$i][thumbnail] = $thumb1;
        elseif (file_exists($thumb2)) $list[$i][thumbnail] = $thumb2;
        elseif (file_exists($thumb3)) $list[$i][thumbnail] = $thumb3;
        elseif (file_exists($thumb4)) $list[$i][thumbnail] = $thumb4;

    }
    return $list;
}

// 입력, 수정
function mw_set_united_search($gr_id, $bo_table, $wr_id, $wr_parent=0)
{
    global $g4, $write_table, $mwus;

    $us_table = $mwus[search_table];

    $is_new = false;
    $sql_where = "gr_id = '$gr_id' and bo_table = '$bo_table' and wr_id = '$wr_id'";

    $sql = "select wr_id from $us_table where $sql_where";
    $row = sql_fetch($sql);

    if (!$row)
	$is_new = true;

    $sql = "select * from $write_table where wr_id = '$wr_id'";
    $row = sql_fetch($sql);

    $row[wr_subject] = addslashes($row[wr_subject]);
    $row[wr_content] = addslashes($row[wr_content]);

    $sql_common = "
	 gr_id = '$gr_id'
	,bo_table = '$bo_table'
	,wr_id = '$row[wr_id]'
	,wr_parent = '$row[wr_parent]'
	,wr_is_comment = '$row[wr_is_comment]'
	,mb_id = '$row[mb_id]'
	,wr_option = '$row[wr_option]'
	,wr_subject = '$row[wr_subject]'
	,wr_content = '$row[wr_content]'
	,wr_datetime = '$row[wr_datetime]'";

    if ($is_new)
	sql_query("insert into $us_table set $sql_common");
    else
	sql_query("update $us_table set $sql_common where $sql_where");
}

// 삭제
function mw_del_united_search($gr_id, $bo_table, $wr_id, $wr_parent=0)
{
    global $mwus;
    if ($wr_parent)
        sql_query("delete from $mwus[search_table] where gr_id = '$gr_id' and bo_table = '$bo_table' and wr_parent = '$wr_parent'");
    else
	sql_query("delete from $mwus[search_table] where gr_id = '$gr_id' and bo_table = '$bo_table' and wr_id = '$wr_id'");
}

// 스킨 디렉토리 얻음
function mwus_skin_dir()
{
    $result_array = array();

    $dirname = "skin/";
    $handle = opendir($dirname);
    while ($file = readdir($handle)) 
    {
        if($file == "."||$file == "..") continue;

        if (is_dir($dirname.$file)) $result_array[] = $file;
    }
    closedir($handle);
    sort($result_array);

    return $result_array;
}

// 사이트 검색
function mw_get_united_search_site($stx, $rows=10)
{
    global $g4, $mwus, $page, $is_admin, $member;

    if (!is_numeric($page)) $page = 1;

    // 인기검색어
    $sql = " insert into $g4[popular_table] set pp_word = '$stx', pp_date = '$g4[time_ymd]', pp_ip = '$_SERVER[REMOTE_ADDR]' ";
    sql_query($sql, FALSE);

    $sql_common = " from $mwus[site_table] ";
    $sql_search = " where ss_status = '1' ";
    $sql_order = " order by ss_order desc ";

    $stx = explode(" ", $stx);
    $sql_search2 = "";
    for ($i=0, $m=count($stx); $i<$m; $i++)
    {
        $stx[$i] = trim($stx[$i]);
        if (!$stx[$i]) continue;

        if ($sql_search2 != "") {
            if ($mwus[us_sop] == "and") {
                $sql_search2 .= " and ";
            }
            else {
                $sql_search2 .= " or ";
            }
        }
        $sql_search2 .= " (INSTR(ss_name, '{$stx[$i]}') or INSTR(ss_detail, '{$stx[$i]}') or INSTR(ss_url, '{$stx[$i]}')) ";
    }
    $sql_search .= " and  ($sql_search2) ";

    $sql = "select count(*) as cnt
	    $sql_common
	    $sql_search";
    $row = sql_fetch($sql);
    $total_count = $row[cnt];

    $total_page  = @ceil($total_count / $rows);  // 전체 페이지 계산
    if ($page == "") { $page = 1; } // 페이지가 없으면 첫 페이지 (1 페이지)
    $from_record = ($page - 1) * $rows; // 시작 열을 구함  */

    $sql = "select *
	    $sql_common
	    $sql_search
	    $sql_order
	    limit $from_record, $rows ";
    $qry = sql_query($sql);

    $list = array();
    $list[total_page] = $total_page;

    for ($i=0; $row=sql_fetch_array($qry); $i++)
    {
        if ($row && !$row[ss_url2])
            $row[ss_url2] = $row[ss_url];

        if ($row && !$row[ss_mobile2])
            $row[ss_mobile2] = $row[ss_mobile];

	$list[$i] = $row;
    }
    return $list;
}

// 바로가기 검색
function mw_get_united_search_direct($stx)
{
    global $g4, $mwus, $page, $is_admin, $member;

    // 인기검색어
    $sql = " insert into $g4[popular_table] set pp_word = '$stx', pp_date = '$g4[time_ymd]', pp_ip = '$_SERVER[REMOTE_ADDR]' ";
    sql_query($sql, FALSE);

    $sql_common = " from $mwus[direct_table] ";
    $sql_search = " where dr_status = '1' ";
    $sql_order = "  ";

    $stx = explode(" ", $stx);
    $sql_search2 = "";
    for ($i=0, $m=count($stx); $i<$m; $i++)
    {
        $stx[$i] = trim($stx[$i]);
        if (!$stx[$i]) continue;

        if ($sql_search2 != "") {
            if ($mwus[us_sop] == "and") {
                $sql_search2 .= " and ";
            }
            else {
                $sql_search2 .= " or ";
            }
        }
        $sql_search2 .= " (INSTR(dr_name, '{$stx[$i]}') or INSTR(dr_keyword, '{$stx[$i]}') or INSTR(dr_url, '{$stx[$i]}')) ";
    }
    $sql_search .= " and  ($sql_search2) ";

    $sql = "select *
	    $sql_common
	    $sql_search
	    $sql_order
	    limit 1";
    $row = sql_fetch($sql);

    if ($row && !$row[dr_url2])
        $row[dr_url2] = $row[dr_url];

    return $row;
}
